<?php

class CurrencyModel extends Model{

    public $Model = array();

    public function _initialize(){
        $this->Model['CurrencyUser'] = new Model('CurrencyUser');
        $this->Model['CurrencyMarket'] = new Model('CurrencyMarket');
        $this->Model['CurrencyAddress'] = new Model('CurrencyAddress');
        $this->Model['PayModel'] = new PayModel();
        $this->Model['Member'] = new MemberModel();
    }

    //获取对应币种，该会员的资产
    public function getCurrencyUser($uid,$cid){
        $where['member_id']=$uid;
        $where['currency_id']=$cid;
        $rs=$this->Model['CurrencyUser']->field('*,(num+forzen_num) as count')->where($where)->find();
        return $rs;
    }

    //添加用户对于的币种金额
    public function addCurrencyUser($uid,$cid){
        $data['member_id']=$uid;
        $data['currency_id']=$cid;
        $data['num']=0;
        $data['forzen_num']=0;
        $data['status']=0;
        $rs=$this->Model['CurrencyUser']->add($data);
        if($rs){
            return true;
        }else{
            return false;
        }
    }
    //获得交易币市场
    public function getMarket(){
        $list=$this->Model['CurrencyMarket']->where('is_lock=0 ')->order('sort')->select();
        return $list;
    }

    //获取全部币种信息
    public function currency(){
        $list=$this->order('sort')->select();
        return $list;
    }
    //获取单独币种信息
    public function currency_one($id,$field='*'){
        $list=$this->field($field)->where("currency_id=".$id)->find();
        return $list;
    }


    //获取单独币种信息
    public function getCurrencyByCurrencyMark($mark,$field='*'){
        $markArr = explode('_', $mark);
        if(count($markArr)!=2){
            return false;
        }
        if($markArr[0]=='CNY'){
            $where['currency_id'] = 0;
        }else{
            $currency_id = $this->where(array('currency_mark'=>$markArr[0]))->getField('currency_id');
            if(!$currency_id) return  false;
            $where['currency_id'] = $currency_id;
        }
        if($markArr[1]=='CNY'){
            $where['trade_currency_id'] = 0;
        }else{
            $currency_id = $this->where(array('currency_mark'=>$markArr[1]))->getField('currency_id');
            if(!$currency_id) return  false;
            $where['trade_currency_id'] = $currency_id;
        }
        $list=$this->Model['CurrencyMarket']->field($field)->where($where)->find();
        if($list){
            $list['currency_mark'] = $markArr[0];
            $list['trade_currency_mark'] = $markArr[1];
        }
        return $list;
    }

    public function getTradeCurrency(){
        $list = $this->Model['CurrencyMarket']->field('trade_currency_id')->where('is_lock=0 ')->order('sort')->group('trade_currency_id')->select();
        foreach ($list as $key => $value) {
            $data[] = $this->getCurrencynameById($value['trade_currency_id']);
        }
        return $data;
    }

    /**
      * 实例化币种
      * @param unknown $currency_id   币种id
      * @return unknown
      */
    public function getCurrencynameById($currency_id){
        if ($currency_id==0){
            return array('currency_name'=>'人民币','currency_mark'=>'CNY','currency_buy_fee'=>0,'currency_sell_fee'=>0);
        }
        $where['currency_id']= $currency_id;
        
        $list = $this->field('currency_name,currency_logo,currency_mark,currency_withdraw_max,currency_withdraw_fee,currency_withdraw_min')->where($where)->find();
        return $list;
    }

    public function getCurrencyByMarketId($market_id=0){
        $where['market_id']=array('eq',$market_id); 
        //获取交易币种信息
        $list= $this->Model['CurrencyMarket']->field("currency_id,price_up,price_down,currency_buy_fee,currency_sell_fee,trade_currency_id,is_lock")->where($where)->find();
        if ($list) {
            return $list;    
        }else{
            return false;
        }
    }
    /**
      *
      * @param int $currency_id 币种id
      * @return array 币种结果集
      */
    public  function  getCurrencyByCurrencyId($currency_id=0){
        if (empty($currency_id)) {
            $where['currency_id']=array('gt',$currency_id);
        }else{
            $where['currency_id']=array('eq',$currency_id);
        }   
        //获取交易币种信息
        $list= $this->field("currency_id,price_up,price_down,trade_currency_id,rpc_url,rpc_pwd,rpc_user,port_number")->where($where)->select();
        if (!empty($currency_id)) {
            return $list[0];    
        }else{
            return $list;
        }
    }


    /**
      * 设置用户资金表 字段值
      * @param int $member_id  用户id
      * @param int $currenty_id 币种id
      * @param string $key  字段名称
      * @param string $value 字段值
      * @return  boolean 返回执行结果
      */
    public function  setCurrentyMemberByMemberId($member_id,$currenty_id,$key,$value){
        return   $this->Model['CurrencyUser']->where("member_id=$member_id and  currency_id=$currenty_id")->setField($key,$value);
    }


    /**
      *  获取当前登陆账号指定币种的金额
      * @param int $currency_id 币种ID
      * @param char $field  num  forzen_num
      * @return array 当前登陆人账号信息
      */
    public  function getUserMoney($member_id,$currency_id,$field){
        if (empty($currency_id)){
            switch ($field){
                case 'num':$field='rmb';break;
                case 'forzen_num':$field='forzen_rmb';break;
                default:$field='rmb';
            }
            $currency_user = $this->Model['Member']->field('rmb,forzen_rmb')->where("member_id={$member_id}")->find();
        }else {
            $currency_user= $this->Model['CurrencyUser']->field('num,forzen_num')->where("member_id={$member_id} and currency_id=$currency_id")->find();
        }
        return  isset($currency_user[$field])?$currency_user[$field]:0;
    }

    /**
     *
     * @param int  $num 数量
     * @param float $price 价格
     * @param char $type 买buy 卖sell
     * @param $currency_id 交易币种
     */
    public function  checkUserMoney($num,$price,$type,$member_id,$currency){
        //获取交易币种信息
        if ($type=='buy'){
            // $trade_money=$num*$price*(1+$currency['currency_buy_fee']/100);
            $trade_money=$num*$price;
            $currency_id=$currency['trade_currency_id'];
        }else {
            $trade_money=$num;
            $currency_id=$currency['currency_id'];
        }
        //和自己的账户做对比 获取账户信息
        $money=$this->getUserMoney($member_id,$currency_id, 'num');
        if ($money<$trade_money){
            return true;
        }else{
            return false;
        }
    }

    /**
      * 设置账户资金
      * @param int $currency_id  币种ID
      * @param int $num 交易数量
      * @param char $inc_dec  setDec setInc 是加钱还是减去
      * @param char forzen_num num
      */
    public  function setUserMoney($member_id,$currency_id,$num,$inc_dec,$field){
        $inc_dec=strtolower($inc_dec) ;
        $field=strtolower($field) ;
        //允许传入的字段
        if (!in_array($field, array('num','forzen_num'))){
            return false;
        }
        //如果是RMB
        if ($currency_id==0){
            //修正字段
            switch ($field){
                case 'forzen_num': $field='forzen_rmb';break;
                case 'num': $field='rmb';break;
            }
            $version = $this->Model['Member']->where("member_id=$member_id")->getField('version');
            $data['version'] = array('exp',"version+1");
            switch ($inc_dec){
                case 'inc':
                    $data[$field] = array('exp',"$field+$num");// $num;
                    $msg= $this->Model['Member']->where("member_id=$member_id and version=$version")->save($data);
                    break;
                case 'dec':
                    $data[$field] = array('exp',"$field-$num");// $num;
                    $msg= $this->Model['Member']->where("member_id=$member_id and version=$version")->save($data);
                    break;
                default:return false;
            }
            return $msg;
        }else{
            $version = $this->Model['CurrencyUser']->where("member_id=$member_id and currency_id=$currency_id")->getField('version');
            $data['version'] = array('exp',"version+1");
            switch ($inc_dec){
                case 'inc':
                    $data[$field] = array('exp',"$field+$num");// $num;
                    $msg= $this->Model['CurrencyUser']->where("member_id=$member_id and currency_id=$currency_id and version=$version")->save($data);
                    break;
                case 'dec':
                    $data[$field] = array('exp',"$field-$num");// $num;
                    $msg= $this->Model['CurrencyUser']->where("member_id=$member_id and currency_id=$currency_id and version=$version")->save($data);
                    break;
                default:return false;
            }
            return $msg;
        }
    }

    public function set_in_url($member_id,$cu_id){
        $this->startTrans();
        $info = $this->Model['CurrencyUser']->field('version,in_url,currency_id')->where(array('cu_id'=>$cu_id,'member_id'=>$member_id))->find();
        if(!$info){
            return false;
        }
        if($info['in_url']){
            return false;
        }
        $currency = $this->currency_one($info['currency_id'],'rpc_user,rpc_pwd,rpc_url,port_number,rpc_open');
        if($currency['rpc_open']==1){
            $address = $this->Model['PayModel']->new_address($member_id,$currency);
            $data = array(
                'in_url'=>$address,
                'version'=>$info['version']+1,
            );
            $r[] = $this->Model['CurrencyUser']->where(array('cu_id'=>$cu_id,'member_id'=>$member_id,'version'=>$info['version']))->save($data);
        }else{
            $address = $this->Model['CurrencyAddress']->where(array('status'=>0,'currency_id'=>$info['currency_id']))->find();
            $data = array(
                'in_url'=>$address['address'],
                'version'=>$info['version']+1,
            );
            $dataAddress = array(
                'status'=>1,
                'member_id'=>$member_id,
                'version'=>$address['version']+1,
            );
            $r[] = $this->Model['CurrencyUser']->where(array('cu_id'=>$cu_id,'member_id'=>$member_id,'version'=>$info['version']))->save($data);
            $r[] = $this->Model['CurrencyAddress']->where(array('address'=>$address['address'],'version'=>$address['version']))->save($dataAddress);
        }
        //更新
        if(!in_array(false, $r)){
            $this->commit();
            return $data['in_url'];
        }else{
            $this->rollback();
            return false;
        }
    }

    public function get_in_url($member_id,$cu_id){
        return  $this->Model['CurrencyUser']
                        ->where(array('cu_id'=>$cu_id,'member_id'=>$member_id))
                        ->getField('in_url');
    }
}